#!perl -w
use strict;

my $exif_tag = "mexif_tagdb_t";
conv( "exif-exif.txt" );
conv( "exif-gps.txt" );
conv( "exif-interop.txt" );

sub conv
{
    my $fn = shift();

    open( X, "<$fn" );
    my @x = <X>;
    close( X );
    chomp( @x );

    my $ifd     = "";
    my $macro   = "";
    my $prefix  = "";
    my $output  = "";
    my $header  = "";
    my %name    = ();
    my %desc    = ();
    my %type    = ();
    foreach my $l ( @x )
    {
        next if ( $l =~ /^##/ );
        next if ( $l =~ /^\s*$/ );
        if ( $l =~ /^#/ )
        {
            my @y = split( /\s+/, $l );
            shift( @y );
            if ( $y[0] eq 'ifd' )       { $ifd    = $y[1]; }
            if ( $y[0] eq 'prefix' )    { $prefix = $y[1]; }
            if ( $y[0] eq 'output' )    { $output = $y[1]; }
            if ( $y[0] eq 'header' )    { $header = $y[1]; }
        }
        else
        {
            my @y = split( /\s+/, $l );
            my $key = sprintf( "%08d", int( $y[0] ) );
            $name{$key} = $y[1];

            $y[2] =~ s/_/ /g;
            $desc{$key} = $y[2];

            $y[3] =~ s/_/ /g;
            $type{$key} = $y[3];
        }
    }

    $macro  = "MEXIF_TAGID_" . uc($prefix);
    $prefix = "mexif_" . uc($prefix);

    my @keys = sort keys %name;
    open( C, ">$output" );
    open( H, ">$header" );

    my $def_count = "_$macro\_Count";
    printf( H "#    define %-40s %d\n", $def_count, $#keys + 1 );
    printf( H "\n" );

    printf( H "extern $exif_tag $prefix\_db\[$def_count];\n" );
    printf( H "const $exif_tag* MEXIF_API $prefix\_search( unsigned int tag );\n" );
    printf( H "\n" );
    printf( H "\n" );

    printf( C "$exif_tag $prefix\_db\[$def_count] = \n" );
    printf( C "{\n" );
    foreach my $key ( @keys )
    {
        my $n = $name{$key};
        my $d = $desc{$key};
        my $t = $type{$key};
        my $h = $macro . "_" . $n;

        printf( C "    { %5d, L\"%s\", L\"%s\" }, // %s\n", $key, $n, $d, $t );
        printf( H "#    define %-40s %d\n", $h, int($key) );
    }
    printf( C "};\n" );


    printf( C "\n\n\n" );

    printf( C "const $exif_tag* MEXIF_API $prefix\_search( unsigned int tag )\n" );
    printf( C "{\n" );
    printf( C "    switch( tag )\n" );
    printf( C "    {\n" );
    my $i = 0;
    foreach my $key ( @keys )
    {
        my $n = $name{$key};
        my $d = $desc{$key};
        my $t = $type{$key};
        my $h = $macro . "_" . $n;

        printf( C "    case %-40s : return $prefix\_db + %2d;\n", $h, $i );
        ++$i;
    }
    printf( C "    }\n" );
    printf( C "    return 0;\n" );
    printf( C "};\n" );

    close( C );
    close( H );
}


